const OrganizationService = require('../service/organization');
const UserService = require('../service/user');
const { logger } = require('../utils');
const { mergeAgent, cloudApiClient } = require('../utils');
const { v4 } = require('uuid');

const organizationService = new OrganizationService();
const userService = new UserService();

module.exports = (app) => {
  app.post(`${process.env.VUE_APP_BASE_API}/organization/register`, async (req, res) => {
    let params = {};
    let existUser = false;
    const { body } = req;
    const { mobile } = body;
    try {
      const existOrganization = await organizationService.first({ organizationName: body.ProxyOrganizationName });
      if (existOrganization) {
        res.json({
          code: 50000,
          message: '企业已存在，请勿重复注册',
        });
        return;
      }
      existUser = await userService.first({ mobile });

      const ProxyOrganizationOpenId = v4();
      const openId = v4();
      params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId,
          OpenId: openId,
        }),
        ProxyOrganizationName: body.ProxyOrganizationName,
        ProxyOperatorName: body.ProxyOperatorName,
        UniformSocialCreditCode: body.UniformSocialCreditCode,
        Endpoint: 'PC',
      };
    } catch (err) {
      logger.error({
        ...params,
        Action: 'CreateConsoleLoginUrl',
        message: err,
      });
      res.json({
        code: 50000,
        message: err.message,
        stack: err.stack,
      });
    }
    try {
      const data = await cloudApiClient.CreateConsoleLoginUrl(params);
      if (data.ConsoleUrl) {
        const newOrgInfo = {
          id: params.Agent.ProxyOrganizationOpenId,
          organizationName: params.ProxyOrganizationName,
          organizationOpenId: params.Agent.ProxyOrganizationOpenId,
          uniformSocialCreditCode: params.UniformSocialCreditCode,
        };
        const newUserInfo = {
          openId: params.Agent.ProxyOperator.OpenId,
          userId: params.Agent.ProxyOperator.OpenId,
          mobile,
          userName: params.ProxyOperatorName,
          verified: data.ProxyOperatorIsVerified,
          organizationId: params.Agent.ProxyOrganizationOpenId,
        };
        await organizationService.create(newOrgInfo);
        if (!existUser) {
          // 数据表中不存在该注册信息，需写入
          userService.create(newUserInfo);
        }
        return res.json({
          code: 20000,
          data: {
            ...data,
            ...newOrgInfo,
            token: newUserInfo.openId,
          },
        });
      }
      return res.json({
        code: 50000,
        data: {
          ...data,
        },
      });
    } catch (err) {
      logger.error({
        ...params,
        Action: 'CreateConsoleLoginUrl',
        message: err,
      });
      res.json({
        code: 50000,
        message: err.message,
        stack: err.stack,
      });
    }
  });
};
